package com.atguigu.crowd.filter;

import com.atguigu.crowd.util.AccessPassResources;
import com.atguigu.crowd.util.CrowdConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author yzt
 * @create 2021-09-23 16:10
 */
@Component
public class CrowdZuulFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 1.获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 2.通过RequestContext对象获取当前请求对象（ 框架底层是借助 ThreadLocal 从当前线程上获取事先绑定的 Request 对象）
        HttpServletRequest request = requestContext.getRequest();
        // 3.获取 servletPath 值
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        if(AccessPassResources.PASS_RES_SET.contains(servletPath)){
            return false;
        }
        if(AccessPassResources.judgeAccessStaticResources(servletPath)){
            return false;
        }
        String detailProjectPath = "/project/get/detail/project/";
        if(servletPath.contains(detailProjectPath)){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext requestContext = RequestContext.getCurrentContext();

        HttpServletRequest request = requestContext.getRequest();

        HttpSession session = request.getSession();

        Object loginMember = session.getAttribute("loginMember");

        if(loginMember == null){
            HttpServletResponse response = requestContext.getResponse();

            session.setAttribute("message", CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);
            try {
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
